<template>
  <BasicModal v-bind="$attrs" @register="registerModal" destroyOnClose :title="title" :width="1024" @ok="handleSubmit">
    <BasicForm @register="registerForm" ref="formRef">
      <template #billTypeSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择单据类型" @search="openBillType" />
      </template>
      <template #materialSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择料品编码" @search="open" />
      </template>
      <template #unitSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择单位" @search="openUnit" />
      </template>
      <template #customerSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择客户" @search="openCustomer" />
      </template>
      <template #orderOrganizationSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择接单组织" @search="openOrganization(1)" />
      </template>
      <template #produceOrganizationSlot="{ model, field }">
        <a-input-search :disabled="isDetail" v-model:value="model[field]" placeholder="请选择生产组织" @search="openOrganization(2)" />
      </template>
    </BasicForm>
    <!-- 子表单区域 -->
    <a-tabs v-model:activeKey="activeKey" animated @change="handleChangeTabs">
      <a-tab-pane tab="订单明细" key="busSaleOrderItem" :forceRender="true">
        <JVxeTable
          keep-source
          resizable
          ref="busSaleOrderItem"
          :loading="busSaleOrderItemTable.loading"
          :columns="busSaleOrderItemTable.columns"
          :dataSource="busSaleOrderItemTable.dataSource"
          :height="340"
          :rowNumber="true"
          :rowSelection="true"
        >
        </JVxeTable>
      </a-tab-pane>
    </a-tabs>
  </BasicModal>
  <!-- 单据类型 -->
  <billTypeSelectModel @register="billTypeRegModal" @getSelectResult="billTypehandleSuccess" v-bind="getBindValue"></billTypeSelectModel>
  <!-- 料品 -->
  <materialSelectModel @register="materialRegModal" @getSelectResult="materialhandleSuccess" v-bind="getBindValue"></materialSelectModel>
  <!-- 单位 -->
  <unitSelectModel @register="unitRegModal" @getSelectResult="unithandleSuccess" v-bind="getBindValue"></unitSelectModel>
  <!-- 客户 -->
  <customerSelectModel @register="customerRegModal" @getSelectResult="customerhandleSuccess" v-bind="getBindValue"></customerSelectModel>
  <!-- 组织 -->
  <organizationSelectModel
    @register="organizationRegModal"
    @getSelectResult="organizationhandleSuccess"
    v-bind="getBindValue"
  ></organizationSelectModel>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive } from 'vue';
import { BasicModal, useModalInner, useModal } from '/@/components/Modal';
import { BasicForm, useForm } from '/@/components/Form/index';
import { JVxeTable } from '/@/components/jeecg/JVxeTable';
import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods.ts';
import { formSchema, busSaleOrderItemColumns } from '../BusOrderCenter.data';
import { saveOrUpdate, queryChangeRecordById } from '../BusOrderCenter.api';
import unitSelectModel from '/@/views/components/unitSelectModel.vue';
import materialSelectModel from '/@/views/components/materialSelectModel.vue';
import customerSelectModel from '/@/views/components/customerSelectModel.vue';
import organizationSelectModel from '/@/views/components/organizationSelectModel.vue';
import billTypeSelectModel from '/@/views/components/billTypeSelectModel.vue';

// Emits声明
const emit = defineEmits(['register', 'success']);
const isUpdate = ref(true);
const isDetail = ref(false)
const refKeys = ref(['busSaleOrderItem']);
const activeKey = ref('busSaleOrderItem');
const busSaleOrderItem = ref();
const tableRefs = { busSaleOrderItem };
const busSaleOrderItemTable = reactive({
  loading: false,
  dataSource: [],
  columns: busSaleOrderItemColumns,
});
//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, updateSchema }] = useForm({
  labelWidth: 120,
  schemas: formSchema,
  showActionButtonGroup: false,
  baseColProps: { span: 8 },
});
//表单赋值
const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  //重置表单
  await resetFields();
  setModalProps({ confirmLoading: false, showCancelBtn: !!data?.showFooter, showOkBtn: !!data?.showFooter });
  isUpdate.value = !!data?.isUpdate;
  isDetail.value = !!data?.isDetail;
  if (unref(isUpdate)) {
    //表单赋值
    await setFieldsValue({
      ...data.record,
    });
    requestSubTableData(queryChangeRecordById, { orderCenterId: data?.record?.id }, busSaleOrderItemTable);
    await updateSchema([
      {
        label: '单据类型ID',
        field: 'billTypeId',
        component: 'Input',
        show: false,
      },
      {
        label: '单据类型',
        field: 'billTypeName',
        component: 'Input',
        slot: 'billTypeSlot',
        dynamicRules: () => {
          return [{ required: true, message: '请输入单据类型!' }];
        },
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '订单渠道',
        field: 'orderChannel',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_order_channel',
          stringToNumber: true,
          disabled: true,
        },
      },
      {
        label: '单据编号',
        field: 'billCode',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '行号',
        field: 'rowNumber',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '料品ID',
        field: 'materialId',
        component: 'Input',
        show: false,
      },
      {
        label: '料品编号',
        field: 'materialCode',
        component: 'Input',
        show: false,
      },
      {
        label: '料品',
        field: 'materialName',
        component: 'Input',
        slot: 'materialSlot',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '料品规格',
        field: 'spec',
        component: 'Input',
        show: false,
      },
      {
        label: '单位ID',
        field: 'unitId',
        component: 'Input',
        show: false,
      },
      {
        label: '单位',
        field: 'unitName',
        component: 'Input',
        slot: 'unitSlot',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '订单数量',
        field: 'orderQuantity',
        component: 'InputNumber',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '已交数量',
        field: 'deliveryQuantity',
        component: 'InputNumber',
      },
      {
        label: '订单交期',
        field: 'orderDeliveryDate',
        component: 'DatePicker',
      },
      {
        label: 'D1订单交期',
        field: 'd1',
        component: 'DatePicker',
      },
      {
        label: 'D2订单交期',
        field: 'd2',
        component: 'DatePicker',
      },
      {
        label: 'D3订单交期',
        field: 'd3',
        component: 'DatePicker',
      },
      {
        label: '单据状态',
        field: 'billStatus',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_bill_status',
          disabled: true,
        },
      },
      {
        label: '和云销售订单号',
        field: 'hjSerialNumber',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '评审单号',
        field: 'reviewCode',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '业务员ID',
        field: 'salesmanId',
        component: 'Input',
        show: false,
      },
  {
    label: '业务员',
    field: 'salesmanId',
    component: 'JSelectUserByDept',
    componentProps: {
      isRadioSelection:true,
      rowKey: 'id',
      labelKey: 'realname',
      showButton: false
    },
  },
      {
        label: '客户ID',
        field: 'customerId',
        component: 'Input',
        show: false,
      },
      {
        label: '客户',
        field: 'customerName',
        component: 'Input',
        slot: 'customerSlot',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '接单组织ID',
        field: 'orderOrganizationId',
        component: 'Input',
        show: false,
      },
      {
        label: '接单组织',
        field: 'orderOrganizationName',
        component: 'Input',
        slot: 'orderOrganizationSlot',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '生产组织ID',
        field: 'produceOrganizationId',
        component: 'Input',
        show: false,
      },
      {
        label: '生产组织',
        field: 'produceOrganizationName',
        component: 'Input',
        slot: 'produceOrganizationSlot',
      },
      {
        label: 'BOM是否完整',
        field: 'bomComplete',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_bom_complete',
          stringToNumber: true,
        },
      },
      {
        label: '非完整BOM是否安排生产',
        field: 'notCompleteProduce',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_not_complete_produce',
          stringToNumber: true,
        },
      },
      {
        label: '异步状态',
        field: 'syncStatus',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_sync_status',
          stringToNumber: true,
          disabled: true,
        },
      },
      {
        label: '备注',
        field: 'remark',
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      {
        label: '第三方编码',
        field: 'thirdPartyCode',
        ifShow: false,
        component: 'Input',
        componentProps: {
          disabled: true,
        },
      },
      // TODO 主键隐藏字段，目前写死为ID
      {
        label: '',
        field: 'id',
        component: 'Input',
        show: false,
      },
    ]);
  } else {
    await updateSchema([
      {
        label: '单据类型ID',
        field: 'billTypeId',
        component: 'Input',
        show: false,
      },
      {
        label: '单据类型',
        field: 'billTypeName',
        component: 'Input',
        slot: 'billTypeSlot',
        dynamicRules: () => {
          return [{ required: true, message: '请输入单据类型!' }];
        },
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '订单渠道',
        field: 'orderChannel',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_order_channel',
          stringToNumber: true,
          disabled: false,
        },
      },
      {
        label: '单据编号',
        field: 'billCode',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入单据编号!' }];
        },
      },
      {
        label: '行号',
        field: 'rowNumber',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入行号!' }];
        },
      },
      {
        label: '料品ID',
        field: 'materialId',
        component: 'Input',
        show: false,
      },
      {
        label: '料品编号',
        field: 'materialCode',
        component: 'Input',
        show: false,
        dynamicRules: () => {
          return [{ required: true, message: '请输入料品编码!' }];
        },
      },
      {
        label: '料品',
        field: 'materialName',
        component: 'Input',
        slot: 'materialSlot',
        componentProps: {
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入料品!' }];
        },
      },
      {
        label: '料品规格',
        field: 'spec',
        component: 'Input',
        show: false,
      },
      {
        label: '单位ID',
        field: 'unitId',
        component: 'Input',
        show: false,
      },
      {
        label: '单位',
        field: 'unitName',
        component: 'Input',
        slot: 'unitSlot',
        componentProps: {
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入单位' }];
        },
      },
      {
        label: '订单数量',
        field: 'orderQuantity',
        component: 'InputNumber',
        dynamicRules: () => {
          return [{ required: true, message: '请输入订单数量!' }];
        },
      },
      {
        label: '已交数量',
        field: 'deliveryQuantity',
        component: 'InputNumber',
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '订单交期',
        field: 'orderDeliveryDate',
        component: 'DatePicker',
        dynamicRules: () => {
          return [{ required: true, message: '请选择订单交期!' }];
        },
      },
      {
        label: 'D1订单交期',
        field: 'd1',
        component: 'DatePicker',
        dynamicRules: () => {
          return [{ required: true, message: '请选择订单交期!' }];
        },
      },
      {
        label: 'D2订单交期',
        field: 'd2',
        component: 'DatePicker',
        dynamicRules: () => {
          return [{ required: true, message: '请选择订单交期!' }];
        },
      },
      {
        label: 'D3订单交期',
        field: 'd3',
        component: 'DatePicker',
        dynamicRules: () => {
          return [{ required: true, message: '请选择订单交期!' }];
        },
      },
      {
        label: '单据状态',
        field: 'billStatus',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_bill_status',
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入单据状态!' }];
        },
      },
      {
        label: '和云销售订单号',
        field: 'hjSerialNumber',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '评审单号',
        field: 'reviewCode',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '业务员ID',
        field: 'salesmanId',
        component: 'Input',
        show: false,
      },
  {
    label: '业务员',
    field: 'salesmanId',
    component: 'JSelectUserByDept',
    componentProps: {
      isRadioSelection:true,
      rowKey: 'id',
      labelKey: 'realname',
      showButton: false
    },
  },
      {
        label: '客户ID',
        field: 'customerId',
        component: 'Input',
        show: false,
        dynamicRules: () => {
          return [{ required: true, message: '请输入客户ID!' }];
        },
      },
      {
        label: '客户',
        field: 'customerName',
        component: 'Input',
        slot: 'customerSlot',
        componentProps: {
          disabled: false,
        },
        dynamicRules: () => {
          return [{ required: true, message: '请输入客户!' }];
        },
      },
      {
        label: '接单组织ID',
        field: 'orderOrganizationId',
        component: 'Input',
        show: false,
      },
      {
        label: '接单组织',
        field: 'orderOrganizationName',
        component: 'Input',
        slot: 'orderOrganizationSlot',
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '生产组织ID',
        field: 'produceOrganizationId',
        component: 'Input',
        show: false,
        dynamicRules: () => {
          return [{ required: true, message: '请输入生产组织ID!' }];
        },
      },
      {
        label: '生产组织',
        field: 'produceOrganizationName',
        component: 'Input',
        slot: 'produceOrganizationSlot',
        dynamicRules: () => {
          return [{ required: true, message: '请输入生产组织!' }];
        },
      },
      {
        label: 'BOM是否完整',
        field: 'bomComplete',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_bom_complete',
          stringToNumber: true,
        },
      },
      {
        label: '非完整BOM是否安排生产',
        field: 'notCompleteProduce',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_not_complete_produce',
          stringToNumber: true,
        },
      },
      {
        label: '异步状态',
        field: 'syncStatus',
        component: 'JDictSelectTag',
        defaultValue: 1,
        componentProps: {
          dictCode: 'order_center_sync_status',
          stringToNumber: true,
          disabled: false,
        },
      },
      {
        label: '备注',
        field: 'remark',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
      },
      {
        label: '第三方编码',
        field: 'thirdPartyCode',
        component: 'Input',
        componentProps: {
          disabled: false,
        },
        ifShow: false
      },
      // TODO 主键隐藏字段，目前写死为ID
      {
        label: '',
        field: 'id',
        component: 'Input',
        show: false,
      },
    ]);
  }
  // 隐藏底部时禁用整个表单
  setProps({ disabled: !data?.showFooter });
});
//方法配置
const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
  requestAddOrEdit,
  classifyIntoFormData,
  tableRefs,
  activeKey,
  refKeys
);
async function reset() {
  await resetFields();
  activeKey.value = 'busSaleOrderItem';
  busSaleOrderItemTable.dataSource = [];
}
function classifyIntoFormData(allValues) {
  let main = Object.assign({}, allValues.formValue);
  return {
    ...main, // 展开
    queryChangeRecordById: allValues.tablesValue[0].tableData,
  };
}
const getBindValue = Object.assign({}, '');

const [materialRegModal, { openModal: openMaterialModal }] = useModal();
const [unitRegModal, { openModal: openUnitModal }] = useModal();
const [customerRegModal, { openModal: openCustomerModal }] = useModal();
const [organizationRegModal, { openModal: openOrganizationModal }] = useModal();
const [billTypeRegModal, { openModal: openBillTypeModal }] = useModal();

//打开选择料品
function open() {
  openMaterialModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择单据类型
function openBillType() {
  openBillTypeModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择单位
function openUnit() {
  openUnitModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择客户
function openCustomer() {
  openCustomerModal(true, {
    isUpdate: false,
    showFooter: true,
  });
}
//打开选择组织
function openOrganization(type) {
  openOrganizationModal(true, {
    isUpdate: false,
    showFooter: true,
    type: type,
  });
}

//回写料品
function materialhandleSuccess(val, values) {
  setFieldsValue({
    materialName: val[0].label,
    materialId: val[0].value,
    materialCode: val[0].item.code
  });
}
//回写单位
function unithandleSuccess(val, values) {
  setFieldsValue({
    unitName: val[0].label,
    unitId: val[0].value,
  });
}
//回写客户
function customerhandleSuccess(val, values) {
  setFieldsValue({
    customerName: val[0].label,
    customerId: val[0].value,
  });
}
//回写单据类型
function billTypehandleSuccess(val, values) {
  setFieldsValue({
    billTypeName: val[0].label,
    billTypeId: val[0].value,
  });
}
//回写组织
function organizationhandleSuccess(val, values, type) {
  if (type == 1) {
    setFieldsValue({
      orderOrganizationName: val[0].label,
      orderOrganizationId: val[0].value,
    });
  } else if (type == 2) {
    setFieldsValue({
      produceOrganizationName: val[0].label,
      produceOrganizationId: val[0].value,
    });
  }
}
//设置标题
const title = computed(() => (unref(isDetail) ? '详情' : !unref(isUpdate) ? '新增' : '编辑'));
//表单提交事件
async function requestAddOrEdit(values) {
  console.log("values",values)
  try {
    setModalProps({ confirmLoading: true });
    //提交表单
    await saveOrUpdate(values, isUpdate.value);
    //关闭弹窗
    closeModal();
    //刷新列表
    emit('success');
  } finally {
    setModalProps({ confirmLoading: false });
  }
}
</script>

<style lang="less" scoped>
/** 时间和数字输入框样式 */
:deep(.ant-input-number) {
  width: 100%;
}

:deep(.ant-calendar-picker) {
  width: 100%;
}
</style>